package com.zhangpf.boot.util;

import org.apache.commons.lang3.StringUtils;

/**
 * 字符串脱敏工具类
 * @author lvzhitao
 *
 */
public class DesensiUtil extends StringUtils {
	
	 // 手机号码前三后四脱敏
    public static String mobileEncrypt(String mobile) {
        if (StringUtils.isEmpty(mobile) || (mobile.length() != 11)) {
            return mobile;
        }
        return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    //身份证前三后四脱敏
    public static String idEncrypt(String id) {
        if (StringUtils.isEmpty(id) || (id.length() < 8)) {
            return id;
        }
        return id.replaceAll("(?<=\\w{4})\\w(?=\\w{4})", "*");
    }
    
    //卡号三后四脱敏
    public static String cardEncrypt(String card) {
        if (StringUtils.isEmpty(card) || (card.length() < 8)) {
            return card;
        }
        return card.replaceAll("(?<=\\w{4})\\w(?=\\w{4})", "*");
    }
    
    //姓名截取第一个字脱敏
    public static String nameEncrypt(String name){
    	if (StringUtils.isEmpty(name) || (name.length() < 2)) {
            return name;
        }
    	return "*"+name.substring(1);
    }
    
    /**
     * [电子邮箱] 邮箱前缀仅显示第一个字母，前缀其他隐藏，用星号代替，@及后面的地址显示<例子:g**@163.com>
     * 
     * @param email
     * @return
     */
    public static String emailEncrypt(String email) {
        if (StringUtils.isBlank(email)) {
            return "";
        }
        int index = StringUtils.indexOf(email, "@");
        if (index <= 3)
            return email;
        else
            return StringUtils.rightPad(StringUtils.left(email, 3), index, "*").concat(StringUtils.mid(email, index, StringUtils.length(email)));
    }

    public static void main(String args[]){
    	System.out.println("6214830122027237  "+ DesensiUtil.cardEncrypt("6214830122027237"));
    	System.out.println("123  "+ DesensiUtil.cardEncrypt("123"));
    	
    	System.out.println("15801594671  "+ DesensiUtil.mobileEncrypt("15801594671"));
    	System.out.println("158  "+ DesensiUtil.mobileEncrypt("15801594671"));
    	
    	System.out.println("210503198608020619  "+ DesensiUtil.idEncrypt("210503198608020619"));
    	System.out.println("210  "+ DesensiUtil.idEncrypt("210503198608020619"));
    	
    	System.out.println("吕智涛  "+ DesensiUtil.nameEncrypt("吕智涛"));
    	
    	System.out.println("12321321@qq.com  "+ DesensiUtil.emailEncrypt("12321321@qq.com"));
    }

}
